package ru.spbu.math.android.cbrf.application;

import java.util.List;

import ru.spbu.math.android.cbrf.dataprovider.ProviderManager;
import ru.spbu.math.android.cbrf.model.Category;
import ru.spbu.math.android.cbrf.model.RateType;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class EditOnCategoryClickListener implements OnItemClickListener {

	private static final String TAG = "Application.EditCategoryList";
	private CategoryListAdapter categoryListAdapter;
	private Context context;
	

	public EditOnCategoryClickListener(Context context,
			CategoryListAdapter listAdapter) {
		this.categoryListAdapter = listAdapter;
		this.context = context;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		Category category = (Category) categoryListAdapter.getItem(arg2);
		Log.d(TAG, "select category: " + category.getName());
		List<RateType> rateTypes = ProviderManager.getInstance(context)
				.getRateTypeByCategory(category);

		// set selected category in category list adapter
		categoryListAdapter.setSelectedCategory(category);

		// open RateTypes list dialog

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(category.getName());
		CharSequence[] rateNames = new CharSequence[rateTypes.size()];
		int i = 0;
		for(RateType r: rateTypes){
			rateNames[i] = r.getName();
			i++;
		}
		int size = i;
		boolean[] isChecked = new boolean[size];
		for(i = 0; i < size; i++){
			isChecked[i] = AppConfigure.isCkecked(context, ProviderManager.getInstance(context).getExternalIdByRateType(rateTypes.get(i)));
		}
		EditRateTypeListAdapter rateListAdapter = new EditRateTypeListAdapter(rateTypes, context);
		builder.setMultiChoiceItems(rateNames, isChecked, new EditOnRateTypeClickListener(rateListAdapter, context));
		builder.show();

	}
}